package com.example.screenapppush

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.media.projection.MediaProjection
import android.media.projection.MediaProjectionManager
import android.os.Build
import android.os.Bundle
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult
import androidx.appcompat.app.AppCompatActivity


class MainActivity : AppCompatActivity() {

    var mediaProjectionManager:MediaProjectionManager ?= null;

   lateinit var  registerForActivityResult :ActivityResultLauncher<Intent>
    fun checkPermission(): Boolean {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            requestPermissions(
                arrayOf(
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                ), 1
            )
        }
        return false
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        checkPermission();
         registerForActivityResult = registerForActivityResult(StartActivityForResult()) {


            if (it.resultCode == RESULT_OK) {

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    val intent = Intent(this@MainActivity, ScreenPushService::class.java)
                    intent.putExtra("resultCode", it.resultCode)
                    intent.putExtra("data", it.data)
                    startForegroundService(intent)
                }else {
                    it.data?.let { intent ->
                        val mediaProjection: MediaProjection = mediaProjectionManager!!.getMediaProjection(it.resultCode, intent);
                        val socketLive  = SocketLive();
                        socketLive.mediaProjection = mediaProjection
                        socketLive.startWebSocketServer()
                        socketLive.startLive()
                    }
                }

            }
        }
    }

    fun pushScreen(view: View) {
        mediaProjectionManager = getSystemService(MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
        registerForActivityResult.launch(mediaProjectionManager!!.createScreenCaptureIntent())
    }


}